package com.example._04发布确认模式;

import com.example.utils.RabbitMqUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmCallback;

import java.util.UUID;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;

/**
 * @author linjy on 2022/8/8
 * <p>
 * 发布确认模式
 * 1、单个确认
 * 2、批量确认
 * 3、异步批量确认
 */
public class ConfirmMessage {
    public static final int MESSAGE_COUNT = 1000;

    public static void main(String[] args) throws Exception {
        //单个发送
        //publishMessageIndividually();//发布1000个单独确认消息,耗时620ms

        //批量
        //publishMessageBatch();//发布1000个批量确认消息,耗时51ms

        //异步批量确认
        publishMessageAsync();//发布1000个单独确认消息,耗时32ms


    }

    /**
     * 单个发送
     */
    public static void publishMessageIndividually() throws Exception {
        Channel channel = RabbitMqUtils.getChannel();
        //队列声明
        String queueName = UUID.randomUUID().toString();
        channel.queueDeclare(queueName, true, false, false, null);
        //开启发布确认
        channel.confirmSelect();

        long begin = System.currentTimeMillis();

        for (int i = 0; i < MESSAGE_COUNT; i++) {
            String message = i + "";
            channel.basicPublish("", queueName, null, message.getBytes());
            //服务端返回 false 或超时时间内未返回，生产者可以消息重发
            boolean flag = channel.waitForConfirms();
            if (flag) {
                System.out.println("消息发送成功");
            }
        }

        long end = System.currentTimeMillis();
        System.out.println("发布" + MESSAGE_COUNT + "个单独确认消息,耗时" + (end - begin) + "ms");
    }

    /**
     * 批量
     */
    public static void publishMessageBatch() throws Exception {
        Channel channel = RabbitMqUtils.getChannel();
        //队列声明
        String queueName = UUID.randomUUID().toString();
        channel.queueDeclare(queueName, true, false, false, null);
        //开启发布确认
        channel.confirmSelect();
        //批量确认消息大小
        int batchSize = 100;
        //未确认消息个数
        int outstandingMessageCount = 0;
        long begin = System.currentTimeMillis();

        for (int i = 0; i < MESSAGE_COUNT; i++) {
            String message = i + "";
            channel.basicPublish("", queueName, null, message.getBytes());
            outstandingMessageCount++;
            if (outstandingMessageCount == batchSize) {
                channel.waitForConfirms();
                outstandingMessageCount = 0;
            }
        }
        //为了确保还有剩余没有确认消息 再次确认
        if (outstandingMessageCount > 0) {
            channel.waitForConfirms();
        }
        long end = System.currentTimeMillis();
        System.out.println("发布" + MESSAGE_COUNT + "个批量确认消息,耗时" + (end - begin) + "ms");
    }


    /**
     * 异步发布确认
     */
    public static void publishMessageAsync() throws Exception {
        Channel channel = RabbitMqUtils.getChannel();
        //队列声明
        String queueName = UUID.randomUUID().toString();
        channel.queueDeclare(queueName, true, false, false, null);
        //开启发布确认
        channel.confirmSelect();

        /**
         * 保存未确认的消息
         * 线程安全有序的一个哈希表 适用于高并发的情况
         * 1.轻松的将序号与消息进行关联
         * 2.轻松的批量删除条目 只要给到序号
         * 3.支持高并发
         */
        //TODO ConcurrentSkipListMap
        ConcurrentSkipListMap<Long, String> concurrentSkipListMap = new ConcurrentSkipListMap<>();


        //消息确认成功 回调函数
        /**
         * 1.消息的标记
         * 2.是否为批量确认
         */
        ConfirmCallback confirmCallback = (deliveryTag, multiple) -> {
            //2：删除掉已经确认的消息 剩下的就是未确认的消息 TODO
            if (multiple) {
                /**
                 * headMap(K toKey) 方法接受一个参数 toKey，表示最大键的值，然后返回一个新的 ConcurrentNavigableMap，
                 * 该 Map 包含原始 ConcurrentSkipListMap 中所有小于 toKey 的键值对。
                 */
                ConcurrentNavigableMap<Long, String> concurrentNavigableMap = concurrentSkipListMap.headMap(deliveryTag);
                /**
                 * 会删除掉concurrentSkipListMap中对应的数据
                 */
                concurrentNavigableMap.clear();
            } else {
                concurrentSkipListMap.remove(deliveryTag);
            }

            System.out.println("确认的消息：" + deliveryTag);
        };

        //消息确认失败 回调函数
        /**
         * 1.消息的标记
         * 2.是否为批量确认
         */
        ConfirmCallback nackCallback = (deliveryTag, multiple) -> {
            //3:打印下未确认的消息
            System.out.println("未确认的消息：" + deliveryTag + "未确认的消息TAG：" + multiple);
        };

        //准备消息的监听器 监听哪些消息成功了，哪些消息失败了
        //异步通知
        /**
         * 1.监听哪些消息成功了
         * 2.监听哪些消息失败了
         */
        channel.addConfirmListener(confirmCallback, nackCallback);

        //开始时间
        long begin = System.currentTimeMillis();

        //批量发送
        for (int i = 0; i < MESSAGE_COUNT; i++) {
            String message = i + "";
            //1:此处记录下所有要发送的消息
            concurrentSkipListMap.put(channel.getNextPublishSeqNo(), message);

            channel.basicPublish("", queueName, null, message.getBytes());
        }

        long end = System.currentTimeMillis();
        System.out.println("发布" + MESSAGE_COUNT + "个单独确认消息,耗时" + (end - begin) + "ms");
    }
}
